import { reqLogin, reqGetProfile, reqGetUserDetailById } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
const state = { token: getToken() || '', userInfo: {}}
const mutations = {
  setToken(state, newToken) {
    state.token = newToken
    setToken(newToken)
  },
  setUserInfo(state, newUserInfo) {
    state.userInfo = newUserInfo
  },
  removeUserInfo(state) {
    state.userInfo = {}
  },
  removeToken(state) {
    state.token = ''
    removeToken()
  }

}
const actions = {
  logout(context) {
    context.commit('removeToken')
    context.commit('removeUserInfo')
  },
  async login(context, data) {
    return new Promise((resolve, reject) => {
      reqLogin(data).then(res => {
        const token = res.data
        context.commit('setToken', token)
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
    // const res = await reqLogin(data)
    // const token = res.data
    // context.commit('setToken', token)
    // return res
  },
  async getUserInfo(context) {
    const { data: data1 } = await reqGetProfile() // data 就是用户基本的资料
    const { data: data2 } = await reqGetUserDetailById(data1.userId) // 包含头像的资料
    const baseResult = {
      ...data1,
      ...data2
    }
    context.commit('setUserInfo', baseResult)
    return baseResult

    // const res = await reqGetProfile()
    // const { data } = res
    // context.commit('setUserInfo', data)
    // return (data)
    // return new Promise((resolve, reject) => {
    //   reqGetProfile().then(res => {
    //     const { data } = res
    //     context.commit('setUserInfo', data)
    //     resolve(data)
    //   }).catch(err => {
    //     reject(err)
    //   })
    // })
  }
}
const getters = {}
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
